package cn.jy.careuplusdoctor.utils;

import java.io.File;
import cn.jy.careuplusdoctor.R;
import cn.jy.careuplusdoctor.entity.Doctor;
import cn.jy.careuplusdoctor.entity.VersionRecs;
import cn.jy.careuplusdoctor.http.HttpHelper;
import cn.jy.careuplusdoctor.http.HttpUrls;
import cn.jy.careuplusdoctor.http.HttpHelper.onHttpListener;
import cn.jy.careuplusdoctor.response.LoginResponse;
import cn.jy.careuplusdoctor.response.VersionRecsResponse;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * 下载
 * 
 * @Title: CheckNewVersion.java
 * @Package com.example.util
 * @Description: TODO
 * @company: EE教育有限公司
 * @author : Administrator
 * @date 2015-7-15 下午2:43:32
 * @version V1.0
 */
public class CheckNewVersion {
	// 地址
	public static final String	FILE_SAVE_DIR	= Environment.getExternalStorageDirectory().getPath() + File.separator
														+ "CareUPlusDoctor" + File.separator;

	public static void checkNewVersion(final Activity activity) {
		final AlertCommon alert = new AlertCommon(activity);
		HttpHelper.getInstance().update("" + getVersionCode(activity), "1", new onHttpListener<VersionRecsResponse>() {
			@Override
			public void onResponse(VersionRecsResponse data, int code) {
				if (data != null && code == HttpUrls.REQUEST_SUCCESS) {
					VersionRecs versionRecs = data.getVersionRecs();
					if (TextUtils.equals("1", data.getResType()) && versionRecs != null) {
						 File _file = new File(FILE_SAVE_DIR);
						 if (!_file.exists()) {
						 _file.mkdirs();
						 }
						 //版本号不一样实现更新
						 if (!(getVersionName(activity)+"").equals(versionRecs.getVersion())) {
							 String content = "当前版本:["+getVersionName(activity)+"]\n最新版本:["+versionRecs.getVersion()+"]\n更新日期:"+versionRecs.getUpdateDate()+"\n更新说明:"+versionRecs.getInstruction()+"";
							 alert.updateDialog(versionRecs.getDownloadUrl(), FILE_SAVE_DIR,
									 "CareU.apk", content);
						}
					} else {
//						Toast.makeText(activity, "", Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(activity, "网络故障，更新失败", Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	@SuppressLint("NewApi")
	public static void doUpdate(final Activity activity, String url, final String savePath, final String fileName) {
		if (activity == null && !StringUtil.isNotEmpty(url) && !StringUtil.isNotEmpty(savePath)
				&& !StringUtil.isNotEmpty(fileName)) {
			return;
		}
		// final String sdCardPath =
		// Environment.getExternalStorageDirectory().getPath();
		BroadcastReceiver receiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
				long id = prefs.getLong("downloadUpdateId", 0);
				DownloadManager manager = (DownloadManager) activity.getSystemService(Activity.DOWNLOAD_SERVICE);
				Uri uri = manager.getUriForDownloadedFile(id);
				if (uri != null) {
					activity.unregisterReceiver(this);
					Intent i = new Intent(Intent.ACTION_VIEW);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					i.setDataAndType(uri, "application/vnd.android.package-archive");
					activity.startActivity(i);
				}
			}
		};
		File file = new File(savePath + fileName);
		if (file.exists()) {
			file.delete();
		}
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
		DownloadManager manager = (DownloadManager) activity.getSystemService(Activity.DOWNLOAD_SERVICE);
		DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
		down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
		down.setAllowedOverRoaming(false);
		down.setVisibleInDownloadsUi(true);
		down.setTitle("下载应用");
		down.setDestinationInExternalFilesDir(activity, savePath, fileName);
		final long id = manager.enqueue(down);
		prefs.edit().putLong("downloadUpdateId", id).commit();
		activity.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	public static int getVersionCode(Activity activity) {
		if (activity == null) {
			return 0;
		}
		int versionCode = 0;
		try {
			versionCode = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	public static float getVersionCodeFloat(Activity activity) {
		if (activity == null) {
			return 0;
		}
		int versionCode = 0;
		try {
			versionCode = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}
	public static String getVersionName(Activity activity) {
		if (activity == null) {
			return "";
		}
		String versionName = "";
		try {
			versionName = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}
}
